package ngat.oss.simulation;

import java.util.*;

import ngat.phase2.*;

/** Basic implementation of a SelectionHeuristic, chooses the group with 
 * the highest score.
 */ 
public class BasicSelectionHeuristic implements SelectionHeuristic {

    /** Returns the selection of 'best' group from the supplied candidate metrics or null
     * if no suitable group can be found.
     */
    public Metric getBestGroup(List candidates) {

	if (candidates.size() == 0)
	    return null;

	Metric best = new Metric(null, -999);
	best.generator = "BasicSelectionHeuristic.Test";

	Iterator it = candidates.iterator();
	while (it.hasNext()) {

	    Metric test = (Metric)it.next();

	    if (test.score > best.score)
		best = test;

	}

	// if we didnt find any groups then return a null reply here.
	if (best.group == null)
	    return null;

	return best;

    }

    /** Returns the probability of the test metric being selected from the supplied candidate metrics.
     * The test metric must not already be present in the candidate list.
     */
    public double getSelectionProbability(List candidates, Metric test) {

	// First find the test metric's rank by counting no which score better.
	int count = 0;
        Iterator ic = candidates.iterator();
        while (ic.hasNext()) {
            Metric metric = (Metric)ic.next();
            if (metric.score > test.score)
                count++;
        }
	int rank = count+1;
        
	// apply a simple smoothing function reflecting the fact that r=0 has high probability, 
	// r=1 less and so forth but with P decreasing quite slowly and never quite reaches zero
	return 1.0/(1.0+Math.exp(rank - 2.0)/5.0);

    }

}
